package org.geeks.gsredisson.api;

import io.github.openunirest.http.Unirest;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;
import org.junit.Test;

public class HelloApiT {

  @Test
  public void unsafe() throws Exception {
    String source = "http://127.0.0.1:8080/hello/unsafe";
    test(source);
  }

  @Test
  public void safe() throws Exception {
    String source = "http://127.0.0.1:8080/hello/safe";
    test(source);
  }

  public void test(String source) throws Exception {
    while (true) {
      Integer threshold = 7;

      CountDownLatch countDownLatch = new CountDownLatch(threshold);

      IntStream.range(0, threshold)
          .forEach(
              i -> {
                new Runner(source, countDownLatch).start();
              });

      Thread.sleep(2000);

      Unirest.get("http://127.0.0.1:8080/hello/reset").asString();

      Thread.sleep(2000);
    }
  }

  class Runner extends Thread {

    private final String source;

    private final CountDownLatch countDownLatch;

    public Runner(String source, CountDownLatch countDownLatch) {
      this.source = source;
      this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
      countDownLatch.countDown();

      try {
        countDownLatch.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      Unirest.get(source).asString();
    }
  }
}
